<template>
  <div class="login" id="login-app">
    <div class="login-box">
      <img src="../assets/pexels-artem-beliaikin-929192.jpg">
      <el-form
          :model="loginForm"
          status-icon
          :rules="loginRules"
          label-width="100px"
          class="login-container"
      >
        <h3 class="login-title">系统登录</h3>
        <el-tabs v-model="activeTab" type="card" stretch="stretch">
          <el-tab-pane label="验证码登录" name="smsCode">
            <el-form-item
                label="手机号"
                label-width="80px"
                prop="userPhone"
                class="phone"
            >
              <el-input
                  type="input"
                  v-model="loginForm.userPhone"
                  auto-complete="off"
                  placeholder="请输入手机号"
                  style="width: 70%;"
              ></el-input>
              <el-button type="primary" @click="doSendingCode" class="code-button">
                <span v-if="!sending">发送验证码</span>
                <span v-else>{{ countdown }}秒后重发</span>
              </el-button>
            </el-form-item>
            <el-form-item
                label="验证码"
                label-width="80px"
                prop="code"
            >
              <el-input
                  type="input"
                  v-model="loginForm.code"
                  auto-complete="off"
                  placeholder="请输入验证码"
                  style="width: 70%;"
              ></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="密码登录" name="userPassword">
            <el-form-item
                label="手机号"
                label-width="80px"
                prop="username"
                class="username"
            >
              <el-input
                  type="input"
                  v-model="loginForm.userPhone"
                  auto-complete="off"
                  placeholder="请输入手机号"
                  style="width: 70%;"
              ></el-input>
            </el-form-item>
            <el-form-item
                label="密码"
                label-width="80px"
                prop="userPassword"
            >
              <el-input
                  type="userPassword"
                  v-model="loginForm.userPassword"
                  auto-complete="off"
                  placeholder="请输入密码"
                  style="width: 70%;"
              ></el-input>
            </el-form-item>
          </el-tab-pane>

        </el-tabs>

        <div class="mb-2 flex items-center text-sm">
          <el-radio-group v-model="loginForm.isAdmin" class="ml-4" >
            <el-radio label="1" size="large">用户</el-radio>
            <el-radio label="0" size="large" style="padding-bottom: 10%;">管理员</el-radio>
          </el-radio-group>
        </div>

        <!-- 登录和注册按钮 -->
        <el-form-item class="login-submit">
          <el-button type="primary" @click="login" class="login-submit">
            <span v-if="!loading">登录</span>
            <span v-else>登录中...</span>
          </el-button>
          <el-button type="primary" @click="register" class="regsiter-submit">
            <span v-if="!loading">注册</span>
          </el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import {userLogin} from "@/API/UserAPI";
import {sendCode} from "@/API/UserAPI";
import message from "@/utils/message";

export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        userPassword: '',
        userPhone: '',
        code: '',
        isAdmin: -1,
      },
      loading: false, // 是否正在登录中
      sending: false, // 是否正在发送验证码中
      countdown: 60, // 验证码倒计时
      activeTab: 'smsCode', // 当前选择的登录方式
    }
  },
  computed: {
    loginRules() {
      // 定义一个验证手机号的函数
      const validatePhone = (rule, value, callback) => {
        // 使用正则表达式匹配手机号格式
        const phoneReg = /^1[3-9]\d{9}$/
        if (!phoneReg.test(value)) {
          callback(new Error('请输入正确手机号'))
          callback()
        }
      }
      const validateCode = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入验证码'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入密码'))
        } else if (value.length < 6) {
          callback(new Error('密码必须在6位以上'))
        } else {
          callback()
        }
      }
      // 返回验证规则对象
      return {
        userPhone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: validatePhone, trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {validator: validateCode, trigger: 'blur'}
        ],
        userPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {validator: validatePassword, trigger: 'blur'}
        ]
      }
    }
  },

  methods: {
    mounted(){
      this.loginForm.isAdmin = 1;
    },

    async login() {
      if (!this.activeTab) {
        this.$message.error('请选择登录方式')
        return
      }
      if (!this.loginForm.isAdmin) {
        this.$message.error('请选择登录身份')
        return
      }
      // 根据不同的登录方式，验证不同的表单字段
      if (this.activeTab === '密码登录') {
        this.loginForm.userPassword = null;
      } else if (this.activeTab === '验证码登录') {
        this.loginForm.code = null;
      }
      const result = await userLogin(this.loginForm);

      if (result.code === 1) {
        localStorage.setItem("token", result.data);
        message.success(this, "登录成功");
        console.log(result.description);
        if(this.loginForm.isAdmin == 1){
          await this.$router.push('/userHome');
        }else{
          await this.$router.push('/adminHome');
        }

      } else {
        message.error(this, result.description);
      }
    },
    register() {
      this.$router.push('/register')
    },
    doSendingCode() {
      if (this.sending) {
        return
      }
      // 如果没有输入手机号，显示提示信息
      if (!this.loginForm.userPhone) {
        this.$message.error('请输入手机号')
        return
      }
      // 如果输入了手机号，发送请求获取验证码
      sendCode(this.loginForm.userPhone)
          .then((response) => {
            // 如果返回的结果是 true，说明验证码发送成功，显示提示信息，开始倒计时
            if (response.code === 1) {
              this.$message.success('验证码已发送')
              this.sending = true
              this.countdown = 60
              let timer = setInterval(() => {
                this.countdown--
                if (this.countdown === 0) {
                  // 如果倒计时结束，清除定时器，重置状态
                  clearInterval(timer)
                  this.sending = false
                  this.countdown = 60
                }
              }, 1000)
            } else {
              this.$message.error('验证码发送失败')
            }
          })
          .catch((error) => {
            console.log(error)
            this.$message.error('验证码发送失败')
          })
    },
  }
}
</script>


<style scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #333;
  font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;

}

.login-box {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  display: flex;
  font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;

}

.login-box img {
  margin-top: 0px; /*改变图片*/
  width: 70%;
  height: 100%;
  border-top-left-radius: 13px;
  border-bottom-left-radius: 13px;
}

.login-container {
  padding-top: 5%; /*改变白色那部分*/
  display: flex;
  flex-direction: column;
  background-color: white;
  border-top-right-radius: 0px;
  border-bottom-right-radius: 0px;
  background-clip: border-box;
  width: 30%;
  border: 0px solid #eaeaea;
  font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;

  /*box-shadow: 0 0 25px #cac6c6;*/
}

.login-title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
  font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;

}

.login-submit {
  margin-left: 5%;
  font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;

}

.ml-4 {
  margin-left: 30%;
  font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
}

</style>